using System;
using System.Data;
using System.Data.SqlClient;
using EntLibEC.Cmn;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using System.Data.Common;

namespace EntLibEC.Dac
{
	/// <summary>
	/// Summary description for Sequence.
	/// </summary>
	public class SequenceDac
	{
		

		private SequenceDac()
		{
		}

		private static SequenceDac _instance;

		public static SequenceDac GetInstance()
		{
			if ( _instance == null )
			{
				_instance = new SequenceDac();
			}
			return _instance;
		}

		public int Create(string paramTable)
		{
			string sql = " insert into " + paramTable + "(createtime) values(getdate());";
			sql += " set @SysNo = SCOPE_IDENTITY()";

            SqlCommand cmd = new SqlCommand(sql);

			SqlParameter paramSysNo = new SqlParameter("@SysNo", SqlDbType.Int,4);
			paramSysNo.Direction = ParameterDirection.Output;

			cmd.Parameters.Add(paramSysNo);

            int sysno = AppConst.IntNull;
            SqlHelper.ExecuteNonQuery(cmd, out sysno);

            return sysno;
		}

        public int GetNextC2SequenceNumber(int c1SysNo)
        {
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = db.GetStoredProcCommand("usp_GetNextC2SequenceNumber");
            db.AddInParameter(dbCommand, "C1SysNo", DbType.Int32, c1SysNo);
            db.AddOutParameter(dbCommand, "C2SequenceNumber", DbType.Int32, 4);

            db.ExecuteNonQuery(dbCommand);

            return Convert.ToInt32(db.GetParameterValue(dbCommand, "C2SequenceNumber"));
        }

        public int GetNextC3SequenceNumber(int c2SysNo)
        {
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = db.GetStoredProcCommand("usp_GetNextC3SequenceNumber");
            db.AddInParameter(dbCommand, "C2SysNo", DbType.Int32, c2SysNo);
            db.AddOutParameter(dbCommand, "C3SequenceNumber", DbType.Int32, 4);

            db.ExecuteNonQuery(dbCommand);

            return Convert.ToInt32(db.GetParameterValue(dbCommand, "C3SequenceNumber"));
        }

        public int GetNextSequenceNumberForProductIDByC3(int c3SysNo)
        {
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = db.GetStoredProcCommand("usp_GetNextSequenceNumberForProductIDByC3");
            db.AddInParameter(dbCommand, "C3SysNo", DbType.Int32, c3SysNo);
            db.AddOutParameter(dbCommand, "SequenceNumberForProductID", DbType.Int32, 4);

            db.ExecuteNonQuery(dbCommand);

            return Convert.ToInt32(db.GetParameterValue(dbCommand, "SequenceNumberForProductID"));
        }
	}
}
